package org.example.erp.utils;
import org.example.erp.domain.Warehouse;
import org.example.erp.domain.WarehouseArea;
import org.example.erp.domain.WarehouseLocation;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class WarehouseTreeBuild {
    public static class TreeNode {
        private String value;
        private String label;
        private List<TreeNode> children;

        public TreeNode(String value, String label) {
            this.value = value;
            this.label = label;
            this.children = new ArrayList<>();
        }

        public String getValue() {
            return value;
        }

        public void setValue(String value) {
            this.value = value;
        }

        public String getLabel() {
            return label;
        }

        public void setLabel(String label) {
            this.label = label;
        }

        public List<TreeNode> getChildren() {
            return children;
        }

        public void setChildren(List<TreeNode> children) {
            this.children = children;
        }

        public static List<TreeNode> buildTree(List<Warehouse> warehouses) {
            Map<Integer, TreeNode> warehouseMap = new HashMap<>();
            for (Warehouse warehouse : warehouses) {
                if(warehouse.getWarehouseId()!=null){
                    TreeNode warehouseNode = new TreeNode(warehouse.getWarehouseId().toString(), warehouse.getWarehouseName());
                    warehouseMap.put(warehouse.getWarehouseId(), warehouseNode);
                }

            }
            for (Warehouse warehouse : warehouses) {
                for (WarehouseArea area : warehouse.getWarehouseAreas()) {
                        if(area.getWarehouseAreaId()!=null){
                            TreeNode areaNode = new TreeNode(area.getWarehouseAreaId().toString(), area.getWarehouseAreaName());
                            warehouseMap.get(warehouse.getWarehouseId()).getChildren().add(areaNode);
                            for (WarehouseLocation location : area.getWarehouseLocations()) {
                                TreeNode locationNode = new TreeNode(location.getWarehouseLocationCode(), location.getWarehouseLocationName());
                                areaNode.getChildren().add(locationNode);
                            }
                        }
                }
            }
            List<TreeNode> treeNodes = new ArrayList<>(warehouseMap.values());
            return treeNodes;
        }
    }
}
